#!/bin/bash

# ============================================
# 主构建脚本 - 构建所有组件
# ============================================

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查参数
if [ $# -eq 0 ]; then
    log_error "版本参数是必需的"
    echo "用法: $0 <version>"
    echo "示例: $0 v1.1.5"
    exit 1
fi

VERSION=$1

echo ""
echo "================================================"
echo "🚀 开始构建所有组件 - 版本: $VERSION"
echo "================================================"
echo ""

# 获取脚本目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
log_info "脚本位置: $SCRIPT_DIR"

# 切换到脚本目录
cd "$SCRIPT_DIR"

# 记录开始时间
START_TIME=$(date +%s)

# ============================================
# 第一步：更新代码
# ============================================
log_info "拉取最新代码..."
if ! git pull; then
    log_error "Git pull 失败，终止构建"
    exit 1
fi
log_success "代码更新完成"

# ============================================
# 第二步：构建后端 API
# ============================================
echo ""
log_info "开始构建后端 API..."
API_START_TIME=$(date +%s)

if [ -f "$SCRIPT_DIR/build-api.sh" ]; then
    if ! bash ./build-api.sh "$VERSION"; then
        log_error "后端构建失败，终止构建"
        exit 1
    fi
else
    log_error "build-api.sh 文件不存在: $SCRIPT_DIR"
    exit 1
fi

API_END_TIME=$(date +%s)
API_DURATION=$((API_END_TIME - API_START_TIME))
log_success "后端构建完成，耗时: ${API_DURATION}s"

# ============================================
# 第三步：构建前端 Web
# ============================================
echo ""
log_info "开始构建前端 Web..."
WEB_START_TIME=$(date +%s)

if [ -f "$SCRIPT_DIR/build-web.sh" ]; then
    if ! bash ./build-web.sh "$VERSION"; then
        log_error "前端构建失败，终止构建"
        exit 1
    fi
else
    log_error "build-web.sh 文件不存在: $SCRIPT_DIR"
    exit 1
fi

WEB_END_TIME=$(date +%s)
WEB_DURATION=$((WEB_END_TIME - WEB_START_TIME))
log_success "前端构建完成，耗时: ${WEB_DURATION}s"

# ============================================
# 构建完成总结
# ============================================
END_TIME=$(date +%s)
TOTAL_DURATION=$((END_TIME - START_TIME))

echo ""
echo "================================================"
log_success "🎉 所有组件构建完成！"
echo "================================================"
echo -e "${GREEN}版本:${NC} $VERSION"
echo -e "${GREEN}后端耗时:${NC} ${API_DURATION}s"
echo -e "${GREEN}前端耗时:${NC} ${WEB_DURATION}s"
echo -e "${GREEN}总耗时:${NC} ${TOTAL_DURATION}s"
echo -e "${GREEN}后端镜像:${NC} crpi-5fhtvlj50ip555mt.cn-guangzhou.personal.cr.aliyuncs.com/docker-hubes/buding-ai:$VERSION"
echo -e "${GREEN}前端镜像:${NC} crpi-5fhtvlj50ip555mt.cn-guangzhou.personal.cr.aliyuncs.com/docker-hubes/buding-web:$VERSION"
echo ""

# 显示部署状态
log_info "当前部署状态:"
echo "后端 Pods:"
kubectl get pods -n work -l app=buding-ai
echo "前端 Pods:"
kubectl get pods -n work -l app=buding-web

log_success "构建和部署流程全部完成！"